using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public abstract class SuperEnemies : MonoBehaviour
{
    public GameObject[] targets;//查找所有最后防线tag对象
    public GameObject finalTarget;//最后防线、目标的游戏对象，确定最近的目标
    protected NavMeshAgent agent;//对象的寻路网格代理
    public int HP;//生命值
    public float speed;//速度
    public int damage;//攻击力
    public int AttackSpeed;//攻速

    public GameManager manager;

    public bool isNotDead = false;
    protected virtual void Start()
    {
        if (finalTarget == null)
        {
            targets = GameObject.FindGameObjectsWithTag("finalTarget");
            GameObject closestTarget = null;
            float closestDistance = Mathf.Infinity;//将最初的距离设置为无限     
            Vector2 curDistance = transform.position;
            foreach (var target in targets)
            {
                float distance = Vector2.Distance(target.transform.position, curDistance);
                if (distance < closestDistance)
                {
                    closestDistance = distance;
                    closestTarget = target;
                }
            }
            finalTarget = closestTarget;
        }
        if(manager == null)
        {
            manager = FindAnyObjectByType<GameManager>();
        }
        //消除NavMesh puls插件的bug
        agent = GetComponent<NavMeshAgent>();
        agent.updateRotation = false;
        agent.updateUpAxis = false;
        //为代理设置速度
        agent.speed = speed;
    }

    protected virtual void Update()
    {
        PathFinding();
        if (HP <= 0)
        {
            Destroy(gameObject);
        }
    }

    protected virtual void PathFinding()//寻路方法
    {
        agent.SetDestination(finalTarget.transform.position);
    }
    protected virtual void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("tower"))//遇到士兵（这里用tower tag）进行攻击
        {
            AttackTower(collision);
        }
        if(collision.CompareTag("finalTarget")) //最后防线（finalTarget tag）
        {
            manager.FinalTargetGetHurt(1);
            Destroy(gameObject);
        }
    }

    protected virtual void AttackTower(Collider2D collision)//攻击方法
    {
        var tower = collision.GetComponent<TowerHolder>();
        while (tower.health != 0)
        {
            StartCoroutine(Attack(tower));
        }
    }

    public virtual void GetHurt(int damage)
    {
        if (!isNotDead)
        {
            HP -= damage;
        }
    }

    protected virtual IEnumerator Attack(TowerHolder tower)
    {
        yield return new WaitForSeconds(AttackSpeed);
        tower.GetHurt(damage);
    }
}
